package com.example.lab.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.lab.entity.Laboratories;
import com.example.lab.event.LaboratoryStatusChangedEvent;
import com.example.lab.mapper.LaboratoriesMapper;
import com.example.lab.result.PageResult;
import com.example.lab.service.ILabManagersService;
import com.example.lab.service.ILaboratoriesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 实验室信息表 服务实现类
 * </p>
 *
 * @author 布莱恩
 * @since 2025-06-17
 */
@Service
@RequiredArgsConstructor
public class LaboratoriesServiceImpl extends ServiceImpl<LaboratoriesMapper, Laboratories> implements ILaboratoriesService {

    private final ApplicationEventPublisher eventPublisher;

    @Override
    public PageResult<Laboratories> getLaboratories(Integer collegeId, Integer page, Integer limit) {
        QueryWrapper<Laboratories> queryWrapper = new QueryWrapper<>();
        if (collegeId != null) {
            queryWrapper.eq("college_id", collegeId);
        }

        Page<Laboratories> pageResult = page(new Page<>(page, limit), queryWrapper);
        return new PageResult<>(
                pageResult.getRecords(),
                pageResult.getTotal(),
                pageResult.getCurrent(),
                pageResult.getSize()
        );
    }

    @Override
    public Laboratories getLaboratoryById(Integer labId) {
        return getById(labId);
    }

    @Override
    public boolean createLaboratory(Laboratories laboratory) {
        return save(laboratory);
    }

    @Override
    public boolean updateLaboratory(Integer labId, Laboratories laboratory) {
        // 如果只是修改状态字段，则允许更新
        Laboratories existingLab = getById(labId);
        if (existingLab == null) {
            throw new RuntimeException("实验室不存在");
        }

        // 检查是否是只修改状态
        boolean isOnlyUpdatingStatus = laboratory.getStatus() != null
                && (laboratory.getLabName() == null || laboratory.getLabName().equals(existingLab.getLabName()))
                && (laboratory.getLocation() == null || laboratory.getLocation().equals(existingLab.getLocation()))
                && (laboratory.getDescription() == null || laboratory.getDescription().equals(existingLab.getDescription()))
                && (laboratory.getLabCode() == null || laboratory.getLabCode().equals(existingLab.getLabCode()))
                && (laboratory.getCollegeId() == null || laboratory.getCollegeId().equals(existingLab.getCollegeId()));
        if (!isOnlyUpdatingStatus && !isLaboratoryEnabled(labId)) {
            throw new RuntimeException("实验室已禁用，禁止修改非状态字段");
        }

        laboratory.setLabId(labId);
        return updateById(laboratory);
    }

    @Override
    public boolean isLaboratoryEnabled(Integer labId) {
        Laboratories lab = getById(labId);
        // 1表示启用状态
        return lab != null && lab.getStatus() != null && lab.getStatus() == true;
    }

    @Override
    public boolean deleteLaboratory(Integer labId) {

        Laboratories lab = getById(labId);
        if (lab == null) {
            throw new RuntimeException("实验室不存在");
        }

        // 如果实验室是启用状态，则先清理关联的管理员
        if (lab.getStatus()) {
            // 发布实验室禁用事件
            eventPublisher.publishEvent(new LaboratoryStatusChangedEvent(this, labId, false));
        }

        // 删除实验室记录
        return removeById(labId);
    }
}
